<?php
class AdminMemberAction extends Action
{
	/**
	 * 后台会员列表
	 */
	public function member_list(){
		$memberMO = M('Member');
		$opt = $_GET['opt'];
		if($opt == 'del'){
			$id = intval($_GET['id']);
			$memberMO->where("id=$id")->delete();
		}
		
		$searchName = !empty($_GET['username']) ? "hh_member.member_name='".urldecode($_GET['username'])."'" : true;
		$searchType = intval($_GET['member_type']) > 0 ? "hh_member.member_type=".urldecode($_GET['member_type']) : true;
		$where = 'hh_member.member_type=hh_member_type.id and '.$searchName.' and '.$searchType;
		
		vendor('Utils.Page');//分页类
		$sql = 'select count(*) as total from hh_member, hh_member_type where '.$where;
		$count = $memberMO->query($sql);

		$p = isset($_GET['p']) ? $_GET['p'] : 1;
		$page = new Page($count[0]['total'],$p,10);
		
//		$sql = 'select hh_member.*, hh_member_type.type_name,GROUP_CONCAT(hh_member_property.property_name) as property_name FROM ';
//		$sql .= '(hh_member LEFT JOIN (hh_property_bind,hh_member_property) ON hh_member.id=hh_property_bind.member_id and hh_member_property.id=hh_property_bind.property_id),'; 
//		$sql .= 'hh_member_type WHERE hh_member.member_type = hh_member_type.id ';
//		$sql .= 'GROUP BY hh_member.id ';
//		$sql .= 'ORDER BY hh_member.id desc limit '.$page->limitMin.','.$page->offset;
//		$data = $memberMO->query($sql);

		$sql = 'select hh_member.*, hh_member_type.type_name from hh_member, hh_member_type where '.$where;
		$sql .= ' ORDER BY hh_member.id desc limit '.$page->limitMin.','.$page->offset;
		$data = $memberMO->query($sql);
		
		if($opt == 'export'){
			$this->export_member($data);
			return;
		}
		
		$this->assign('members',$data);
		$this->assign('page',$page->getPages());
		
		$typeMO = M('MemberType');
		$typeData = $typeMO->select();
		
		$this->assign('searchUsername',$_GET['username']);
		$this->assign('searchMemberType',$_GET['member_type']);
		$this->assign('typeData',$typeData);
		$this->display();
	}
	
	/** 
	 * 后台会员类型列表
	 */
	public function member_type_list(){
		$typeMO = M('MemberType');
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			$data['type_name'] = htmlspecialchars(trim($_POST['addText']));
			if(!empty($data['type_name']))
				$typeMO->add($data);
		}
		
		$data = $typeMO->order('id desc')->select();
		$this->assign('types',$data);
		$this->display();
	}
	
	/**
	 * 后台会员属性列表
	 */
	public function member_property_list(){
		$propertyMO = M('MemberProperty');
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			$data['property_name'] = htmlspecialchars(trim($_POST['addText']));
			if(!empty($data['property_name']))
				$propertyMO->add($data);
		}
		
		$data = $propertyMO->order('id desc')->select();
		$this->assign('propertys',$data);
		$this->display();
	}
	
	/**
	 * 编辑会员信息
	 */
	public function edit_member(){
		$memberMO = M('Member');
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			$editId = intval($_POST['editId']);
			//$data['member_name'] = strtolower(trim($_POST['username']));
			$data['email'] = trim($_POST['email']);
			$data['member_type'] = intval($_POST['member_type']);
			$data['mobile'] = trim($_POST['mobile']);
			$data['telphone'] = trim($_POST['telphone']);
			$data['qq'] = trim($_POST['qq']);
			$data['address'] = htmlspecialchars($_POST['address']);
			$data['gender'] = intval($_POST['gender']);
			$data['member_pwd'] = htmlspecialchars(trim($_POST['pwd']));
			
			if($editId == 0){
				exit('修改失败!');
			}
			
			$memberAC = new MemberAction();
			if($memberAC->isExistEmail($data['email'])){
				unset($data['email']);
			}
			$rel = $memberAC->check_member($data);
			if($rel != '')
				exit($rel);
			
			$memberMO->where("id=$editId")->save($data);
			return;
		}
		$id = intval($_GET['id']);
		$data = $memberMO->where("id=$id")->select();
		
		$typeMO = M('MemberType');
		$typeData = $typeMO->select();
		
		$this->assign('types',$typeData);
		$this->assign('member',$data[0]);
		$this->display();
	}
	
	/**
	 * 增加会员
	 */
	public function add_member(){
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			$data['member_name'] = strtolower(trim($_POST['username']));
			$data['member_pwd'] = htmlspecialchars(trim($_POST['pwd']));
			$data['email'] = trim($_POST['email']);
			$data['member_type'] = intval($_POST['member_type']);
			$data['mobile'] = trim($_POST['mobile']);
			$data['telphone'] = trim($_POST['telphone']);
			$data['qq'] = trim($_POST['qq']);
			$data['gender'] = intval($_POST['gender']);
			$data['birthday'] = $_POST['birthday'];
			$data['address'] = htmlspecialchars($_POST['address']);
			$data['postcode'] = $_POST['postcode'];
			$data['register_date'] = date('Y-m-d H:i:s');
			
			$cofpwd = htmlspecialchars(trim($_POST['cofpwd']));
			
			$memberAC = new MemberAction();
			$rel = $memberAC->check_member($data);
			if($rel != '')
				exit($rel);
				
			if($data['member_pwd'] != $cofpwd)
				exit('两次密码不一样');
				
			$memberMO = M('Member');
			$memberMO->add($data);
			return;
		}
		$typeMO = M('MemberType');
		$typeData = $typeMO->select();
		
		$this->assign('types',$typeData);	
		
		$this->display();
	}
	
	/**
	 * 修改属性
	 */
	public function edit_property(){
		$id = intval($_POST['id']);
		$data['property_name'] = htmlspecialchars(trim($_POST['property_name']));
		if(empty($data['property_name'])){
			exit('属性名不以为空！');
		}
		
		$typeMO = M('MemberProperty');
		$typeMO->where("id=$id")->save($data);
	}
	
	/**
	 * 修改类型
	 */
	public function edit_member_type(){
		$id = intval($_POST['id']);
		$data['type_name'] = htmlspecialchars(trim($_POST['type_name']));
		if(empty($data['type_name'])){
			exit('类型名不以为空！');
		}
		
		$typeMO = M('MemberType');
		$typeMO->where("id=$id")->save($data);
	}
	/**
	 * 批量导入
	 */
	public function batch_member(){
		set_time_limit(0); 
		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			import('ORG.Net.UploadFile');
		    $upload = new UploadFile();// 实例化上传类
		    $upload->maxSize  = 1048576 ;// 设置附件上传大小
		    $upload->allowExts  = array('xls', 'xlsx');// 设置附件上传类型
		    $upload->savePath =  './Public/Uploads/xls/';// 设置附件上传目录
		    if(!$upload->upload()) {// 上传错误提示错误信息
		       $this->error($upload->getErrorMsg());
		  	 }else{
		  	 	// 上传成功
		        $rel = $upload->getUploadFileInfo();
				
		        //解释excel
		        vendor('Utils.PHPExcel.IOFactory');
   				$readerType = ($rel[0]['extension'] == "xlsx") ? "Excel2007":"Excel5";
   				$objReader = PHPExcel_IOFactory::createReader($readerType);
   				$objPHPExcel = $objReader->load($rel[0]['savepath'].$rel[0]['savename']);
   				$sheet = $objPHPExcel->getActiveSheet();
   				$highestRow = $sheet->getHighestRow(); // 取得总行数
				//$highestColumm = $sheet->getHighestColumn(); // 取得总列数
				
   				$i = 0;
		        $memberMO = M('Member');
				$add = array();
   				for($row = 2; $row<$highestRow; $row++){
   					$member['member_name'] = $sheet->getCellByColumnAndRow(0, $row)->getValue();
   					if(empty($member['member_name']))
   						continue;
   					$member['member_pwd'] = $sheet->getCellByColumnAndRow(1, $row)->getValue();
   					$member['email'] = $sheet->getCellByColumnAndRow(2, $row)->getValue();
   					$member['member_type'] = $sheet->getCellByColumnAndRow(3, $row)->getValue();
   					$member['gender'] = $sheet->getCellByColumnAndRow(4, $row)->getValue();
   					$member['mobile'] = $sheet->getCellByColumnAndRow(5, $row)->getValue();
   					$member['telphone'] = $sheet->getCellByColumnAndRow(6, $row)->getValue();
   					$member['qq'] = $sheet->getCellByColumnAndRow(7, $row)->getValue();
   					$member['birthday'] = $sheet->getCellByColumnAndRow(8, $row)->getValue();
   					$member['address'] = $sheet->getCellByColumnAndRow(9, $row)->getValue();
   					$member['register_date'] = date('Y-m-d H:i:s');
   					
   					$member['member_pwd'] = empty($member['member_pwd']) ? '123456' : $member['member_pwd'];
   					$member['member_type'] = empty($member['member_type']) ? 1 : $member['member_type'];
	        		$member['gender'] = $member['gender'] == '女' ? 0 : 1;
	        		
	        		$add[] = $member;
	        		if($i >= 200){
						$memberMO->addAll($add);
						unset($add);
						$i = 0;
						continue;
					}
					$i++;
   				}
   				$memberMO->addAll($add);
   				exit('导入成功');
		   	}
		}
		$this->assign('postUrl',urlencode(__APP__.'/AdminMember/batch_member'));
		$this->display();
	}
	
	/**
	 * 导出
	 */
	private function export_member($data){
		vendor('Utils.PHPExcel');
   		$objPHPExcel = new PHPExcel();
   		$objPHPExcel->setActiveSheetIndex(0)
			   		->setCellValue('A1', '会员名')
					->setCellValue('B1', '密码')
					->setCellValue('C1', 'email')
					->setCellValue('D1', '会员类型')
					->setCellValue('E1', '性别')
					->setCellValue('F1', '手机号码')
					->setCellValue('G1', '座机号码')
					->setCellValue('H1', 'QQ')
					->setCellValue('I1', '出生日期')
					->setCellValue('J1', '地址')
					->setCellValue('K1', '注册时间');
   		$i = 2;
   		foreach($data as $member){
   			$objPHPExcel->setActiveSheetIndex(0)
   							->setCellValue('A' . $i, $member['member_name'])
							->setCellValue('B' . $i, $member['member_pwd'])
							->setCellValue('C' . $i, $member['email'])
							->setCellValue('D' . $i, $member['type_name'])
							->setCellValue('E' . $i, $member['gender']==1?'男':'女')
							->setCellValue('F' . $i, $member['mobile'])
							->setCellValue('G' . $i, $member['telphone'])
							->setCellValue('H' . $i, $member['qq'])
							->setCellValue('I' . $i, $member['birthday'])
							->setCellValue('J' . $i, $member['address'])
							->setCellValue('K' . $i, $member['register_date']);
			$i++;
   		}
   		
   		$file = Date("YmdHis").'-member.xls';
   		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.$file.'"');
		header('Cache-Control: max-age=0');
		
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}
	
	/**
	 * 删除类型
	 */
	public function del_member_type(){
		$id = intval($_POST['id']);
		if($id == 0)
			return;
			
		$typeMO = M('MemberType');
		$typeMO->where("id=$id")->delete();
	}
	
	/**
	 * 删除属性
	 */
	public function del_member_property(){
		$id = intval($_POST['id']);
		if($id == 0)
			return;

		$typeMO = M('MemberProperty');
		$typeMO->where("id=$id")->delete();
	}
}